import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { message } from 'antd';

import "./index.css";
import InterIP from "../../IP/IP";

// import EmptyCart from "../emptyCart"
export default function AreaCart() {
  const [shops, setShops] = useState([]);

  var navigate = useNavigate();
  let IP = InterIP().props.children;

  useEffect(() => {
    let IP = InterIP().props.children;
    axios.post("http://" + IP + ":3000/index/cart", {
      user_id: document.cookie.split("=")[1],
    }).then((res) => {
      if (res.data.length === 0) {
        navigate("/home/emptyCart");
      }
      var bigArr = res.data;
      axios.post('http://localhost:3000/index/selStore', {}).then((res) => {
        let arr = [];
        bigArr.forEach((v, k) => {
          arr[k] = {
            store_id: '',
            store_name: v.store_name,
            boss_name: '',
            boss_phone: '',
            cart_totalPrice: 0,
            product: [],
          }
        });
        for (let i = 0; i < arr.length; i++) {
          for (let j = i + 1; j < arr.length; j++) {
            if (arr[i].store_name === arr[j].store_name) {
              arr.splice(j, 1);
              j--;
            }
          }
        }
        res.data.forEach((value) => {
          arr.forEach((v) => {
            if (v.store_name === value.store_name) {
              v.store_id = value.store_id;
              v.boss_name = value.boss_name;
              v.boss_phone = value.boss_phone;
            }
          })
        })
        arr.forEach((v) => {
          bigArr.forEach((val) => {
            if (v.store_name === val.store_name) {
              let value = JSON.parse(val.product)
              let smallArr = {
                product_name: value.product_name,
                product_number: value.product_number,
                product_specification: value.product_specification,
                product_price: value.product_price,
                product_img: value.product_img,
                buy_number: value.buy_number,
                product_id: value.product_id,
                store_name: value.store_name,
                cart_id: val.cart_id,
                boss_name: v.boss_name,
                boss_phone: v.boss_phone
              }
              v.product.push(smallArr);
            }
          })
        })
        setShops((shops) => shops = arr);
      })
      // } else {

      // }
    });
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
  // console.log(shops);

  // 商品单选(包括单选店铺里商品金额相加)
  //  全选和单选
  var oCheckedAll = document.getElementsByClassName("checkedAll");
  var oCheckBox = document.getElementsByClassName("checkbox");
  // 究极全选
  function onAllCheckedAll() {
    let newShops = [...shops];

    for (var i = 0; i < oCheckBox.length; i++) {
      if (oCheckBox[i].checked === false) {
        for (var j = 0; j < oCheckBox.length; j++) {
          oCheckBox[j].checked = true;
        }
        // 计算店铺总金额
        for (var a = 0; a < newShops.length; a++) {
          newShops[a].cart_totalPrice = 0;
          for (var b = 0; b < newShops[a].product.length; b++) {
            newShops[a].product[b].checked = true;

            newShops[a].cart_totalPrice +=
              parseFloat(newShops[a].product[b].product_price) *
              newShops[a].product[b].buy_number;
          }
        }
        setShops(newShops);
        return;
      } else if (i === oCheckBox.length - 1) {
        oCheckBox[i].checked = false;
        for (var x = 0; x < oCheckBox.length; x++) {
          oCheckBox[x].checked = false;
        }
        for (var y = 0; y < newShops.length; y++) {
          newShops[y].cart_totalPrice = 0;
        }
        setShops(newShops);
      }
    }
  }
  // 求最终价格
  var sumMoneyAll = 0;
  for (let i = 0; i < shops.length; i++) {
    sumMoneyAll += shops[i].cart_totalPrice;
  }
  // 店铺全选(包括单选店铺里商品金额相加)
  function onChangeAll(k) {
    let newShops = [...shops];
    var oCheckedOne = document.getElementsByClassName("checkone" + k);
    return () => {
      if (oCheckedAll[k].checked) {
        // 清零
        newShops[k].cart_totalPrice = 0;
        for (let i = 0; i < oCheckedOne.length; i++) {
          newShops[k].product[i].checked = true;

          oCheckedOne[i].checked = true;
          newShops[k].cart_totalPrice +=
            parseFloat(newShops[k].product[i].product_price) *
            newShops[k].product[i].buy_number;
        }
      } else {
        for (let i = 0; i < oCheckedOne.length; i++) {
          newShops[k].product[i].checked = false;

          oCheckedOne[i].checked = false;
          newShops[k].cart_totalPrice = 0;
        }
      }
      setShops(newShops);
    };
  }

  // 商品单选(包括单选店铺里商品金额相加)
  function onChangeOne(k, key) {
    let newShops = [...shops];
    var oCheckedOne = document.getElementsByClassName("checkone" + k);

    return () => {
      // 店铺总金额计算
      if (oCheckedOne[key].checked) {
        newShops[k].product[key].checked = true;

        // 添加
        newShops[k].cart_totalPrice +=
          parseFloat(newShops[k].product[key].product_price) *
          newShops[k].product[key].buy_number;
      } else {
        newShops[k].product[key].checked = false;

        // 移去
        newShops[k].cart_totalPrice -=
          parseFloat(newShops[k].product[key].product_price) *
          newShops[k].product[key].buy_number;
      }
      setShops(newShops);
      // 商品全部选择全选按钮亮起
      for (var i = 0; i < oCheckedOne.length; i++) {
        if (oCheckedOne[i].checked) {
          oCheckedAll[k].checked = true;
        } else {
          oCheckedAll[k].checked = false;
          return;
        }
      }
    };
  }

  // 累加累减
  // 点击累减
  function subNum(k, key) {
    let newShops = [...shops];
    var oCheckedOne = document.getElementsByClassName("checkone" + k);
    return () => {
      if (oCheckedOne[key].checked) {
        if (newShops[k].product[key].buy_number > 0) {
          newShops[k].product[key].buy_number--;
          newShops[k].cart_totalPrice -= parseFloat(
            newShops[k].product[key].product_price
          );
        }
        setShops(newShops);
      } else {
        if (newShops[k].product[key].buy_number > 0)
          newShops[k].product[key].buy_number--;
        setShops(newShops);
      }
    };
  }
  // 点击累加
  function addNum(k, key) {
    let newShops = [...shops];
    var oCheckedOne = document.getElementsByClassName("checkone" + k);
    return () => {
      if (oCheckedOne[key].checked) {
        newShops[k].product[key].buy_number++;
        newShops[k].cart_totalPrice += parseFloat(
          newShops[k].product[key].product_price
        );
        setShops(newShops);
      } else {
        newShops[k].product[key].buy_number++;
        setShops(newShops);
      }
    };
  }

  // 单个删除按钮
  function deleteOne(k, key) {
    return () => {
      let newShops = [...shops];
      var oCheckedOne = document.getElementsByClassName("checkone" + k);
      // 请求后台删除数据
      axios.post("http://" + IP + ":3000/index/delgoods", { cart_id: shops[k].product[key].cart_id }).then((res) => {
        if (res.data.code) {
          message.success('删除成功');
        }
      })

      // 删除后商品信息全选的话，店铺全选按钮打开
      let num = 0;
      for (let i = 0; i < oCheckedOne.length; i++) {
        if (oCheckedOne[i].checked) num++;
      }
      if (oCheckedOne.length - 1 === num) oCheckedAll[k].checked = true;

      // 删除数据时，商品金额发生变化
      if (oCheckedOne[key].checked) {
        // 当商品选中时，改变金额
        newShops[k].cart_totalPrice -=
          parseFloat(newShops[k].product[key].product_price) *
          newShops[k].product[key].buy_number;
      }

      // 删除对应数据
      newShops[k].product.splice(key, 1);
      if (newShops[k].product.length === 0) {
        // 如果商品删除完后店铺也删除
        newShops.splice(k, 1);
      }
      if (newShops.length === 0) {
        navigate("/home/emptyCart");
      }
      setShops(newShops);
    };
  }

  // 批量删除
  function moreDelete() {
    let newShops = [...shops];
    let shopsArr = [];
    // 找到选中的商品所对应的商品ID 存到数组里
    for (let i = 0; i < oCheckBox.length; i++) {
      if (oCheckBox[i].checked === true && oCheckBox[i].value !== "on") {
        shopsArr.push(newShops[oCheckBox[i].value.substr(0, 1) * 1].product[oCheckBox[i].value.substr(2) * 1].cart_id);
      }
    }

    // 后台批量删除商品
    axios.post("http://" + IP + ":3000/index/delgoods", { cart_id: shopsArr }).then((res) => {
      if (res.data.code) {
        message.success('删除成功');
      }
    })
    // 前台数据删除
    //遍历所有信息 如果是选中状态 删除对应数据
    for (let i = 0; i < newShops.length; i++) {
      for (let j = 0; j < newShops[i].product.length; j++) {
        if (newShops[i].product[j].checked) {
          newShops[i].product.splice(j, 1);
          j--;
        }
      }
    }
    //删除后让所有复选框为false
    for (let i = 0; i < oCheckBox.length; i++) {
      oCheckBox[i].checked = false
    }
    //如果店铺内商品全删完  商铺信息也删除
    for (let i = 0; i < newShops.length; i++) {
      if (newShops[i].product.length === 0) {
        newShops.splice(i, 1)
        i--;
      }
      if (newShops.length === 0) {
        navigate("/home/emptyCart");
      }
    }
    setShops(newShops);
  }


  // 立即购买按钮
  function buyNow() {
    var newArr = [...shops];

    // 如果总价钱不为0 跳转到 确认订单页面 并 传参
    if (sumMoneyAll !== 0) {
      let shopsArr = [];
      for (let i = 0; i < oCheckBox.length; i++) {
        if (oCheckBox[i].checked === true && oCheckBox[i].value !== "on") {
          shopsArr.push(oCheckBox[i].value);
        }
      }

      var checkedArr = [];
      for (let i = 0; i < shopsArr.length; i++) {
        // 筛选所有选中的商品，扔到 checkedArr 数组
        var shop = shopsArr[i].substr(0, 1) * 1;
        var fruit = shopsArr[i].substr(2, 3) * 1;
        checkedArr.push(newArr[shop].product[fruit]);
      }

      // 跳转页面
      navigate("/home/confirmOrderShop", {
        state: checkedArr,
      });
    } else {
      message.warning("你是想买啥玩意？？？");
    }
  }

  return (
    <div className="areaCart">
      <ul>
        <li className="tyc_fristli">我的购物车</li>
        <li>确认订单信息</li>
        <li className="tyc_lastli">订单提交成功</li>
      </ul>
      <h2>购物车</h2>
      {shops.map((v, k) => {
        return (
          <div key={k}>
            <table border="1">
              <thead>
                <tr>
                  <th>
                    <input
                      type="checkbox"
                      className="checkedAll checkbox"
                      onChange={onChangeAll(k)}
                    />
                  </th>
                  <th className="tyc_mallName">
                    <span>{v.store_name}</span>
                  </th>
                  <th className="tyc_specification">规格</th>
                  <th className="tyc_onePrice">单价</th>
                  <th className="tyc_num">数量</th>
                  <th className="tyc_sumOnePrice">金额</th>
                  <th className="tyc_change">操作</th>
                </tr>
              </thead>
              <tbody>
                {shops[k].product.map((value, key) => {
                  return (
                    <tr key={key}>
                      <td>
                        <input
                          value={k + "," + key}
                          type="checkbox"
                          className={`"checkedone checkbox checkone${k}`}
                          onClick={onChangeOne(k, key)}
                        />
                      </td>
                      <td className="tyc_mail">
                        <div>
                          <img src={value.product_img} alt="" />
                        </div>
                        <span>{value.product_name}</span>
                      </td>
                      <td>
                        {value.product_number}
                        {value.product_specification}
                      </td>
                      <td>
                        ￥<i>{value.product_price}</i>
                      </td>
                      <td className="tyc_addsub_btn">
                        <div onClick={subNum(k, key)}>-</div>
                        <input
                          type="text"
                          defaultValue={value.buy_number}
                          key={value.buy_number}
                        />
                        <div onClick={addNum(k, key)}>+</div>
                      </td>
                      <td>
                        ￥
                        <i>
                          {(
                            parseFloat(value.product_price) * value.buy_number
                          ).toFixed(2)}
                        </i>
                      </td>
                      <td>
                        <span
                          className="tyc_delete"
                          onClick={deleteOne(k, key)}
                        >
                          删除
                        </span>
                      </td>
                    </tr>
                  );
                })}

                <tr>
                  <td colSpan="7" className="tyc_sumPrice">
                    <span>商品金额</span>
                    <strong>
                      ￥<span>{parseFloat(v.cart_totalPrice).toFixed(2)}</span>
                    </strong>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        );
      })}

      <div className="tyc_settleAccounts">
        <div className="tyc_allcheck">
          <em className="allcheckedAll" onClick={onAllCheckedAll}>
            全选
          </em>
          <i onClick={moreDelete}>批量删除</i>
        </div>
        <div className="tyc_settleAccounts_right">
          <span>商品总计</span>
          <strong>
            ￥<span>{sumMoneyAll.toFixed(2)}</span>
          </strong>
          <button onClick={buyNow}>立即购买</button>
        </div>
      </div>
    </div>
  );
}
